package com.wry.im.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <h1> 初始化连接的处理器 <h1>
 *
 * @author wry
 * @since 2023/4/27 14:51
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static final AttributeKey<WebSocketServerHandshaker> ATTR_HAND_SHAKER = AttributeKey.newInstance("ATTR_KEY_CHANNEL_ID");

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        log.debug("HttpServerHandler处理器执行...");
        // 获取子协议
        String subProtocols = request.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
        //握手工厂 设置 uri+协议+不允许扩展
        WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory("ws://",subProtocols,false);
        // 从工厂中实例化一个 握手请求
        WebSocketServerHandshaker handshaker = handshakerFactory.newHandshaker(request);
        if (handshaker == null){
            //握手失败：不支持的协议
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        }else {
            //响应请求:将 握手转交给 channel处理
            handshaker.handshake(ctx.channel(),request);
            //将 channel 与 handshaker 绑定
            ctx.channel().attr(ATTR_HAND_SHAKER).set(handshaker);
        }
    }

}
